import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken, removeToken } from '@/utils/auth'
import router from '@/router'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    // 添加 token
    if (store.getters.token) {
      config.headers['Authorization'] = `Bearer ${getToken()}`
    }

    // 添加请求时间戳，避免缓存
    if (config.method === 'get') {
      config.params = {
        ...config.params,
        _t: Date.now()
      }
    }

    return config
  },
  error => {
    console.error('Request Error:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data

    // 根据你的后端返回结构判断成功状态
    if (res.code === 1) {
      return res
    } else {
      // 业务逻辑错误处理
      const errorMessage = res.msg || '请求失败'

      // 特殊状态码处理
      if (res.code === 401) {
        handleUnauthorized()
        return Promise.reject(new Error('登录状态已过期'))
      }

      // 其他已知错误码处理
      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
        handleTokenExpired()
        return Promise.reject(new Error(errorMessage))
      }

      // 显示错误消息（非 401 错误）
      if (res.code !== 401) {
        Message({
          message: errorMessage,
          type: 'error',
          duration: 5 * 1000
        })
      }

      return Promise.reject(new Error(errorMessage))
    }
  },
  error => {
    // HTTP 错误处理
    if (error.response) {
      const { status, data } = error.response

      switch (status) {
        case 401: {
          handleUnauthorized()
          break
        }

        case 403: {
          Message({
            message: '拒绝访问',
            type: 'error',
            duration: 5 * 1000
          })
          break
        }

        case 404: {
          Message({
            message: '请求地址不存在',
            type: 'error',
            duration: 5 * 1000
          })
          break
        }

        case 500: {
          Message({
            message: '服务器内部错误',
            type: 'error',
            duration: 5 * 1000
          })
          break
        }

        case 502: {
          Message({
            message: '网关错误',
            type: 'error',
            duration: 5 * 1000
          })
          break
        }

        case 503: {
          Message({
            message: '服务不可用',
            type: 'error',
            duration: 5 * 1000
          })
          break
        }

        default: {
          const message = data?.msg || error.message || '网络错误'
          if (status !== 401) {
            Message({
              message: message,
              type: 'error',
              duration: 5 * 1000
            })
          }
          break
        }
      }
    } else if (error.message.includes('timeout')) {
      Message({
        message: '请求超时',
        type: 'error',
        duration: 5 * 1000
      })
    } else if (error.message.includes('Network')) {
      Message({
        message: '网络连接失败',
        type: 'error',
        duration: 5 * 1000
      })
    }

    return Promise.reject(error)
  }
)

// 处理未授权 (401)
function handleUnauthorized() {
  // 清除 token 和用户信息
  removeToken()
  store.commit('user/SET_TOKEN', '')
  store.commit('user/SET_ROLES', [])
  store.commit('user/SET_NAME', '')
  store.commit('user/SET_AVATAR', '')

  // 跳转到登录页
  const currentPath = router.currentRoute.fullPath
  if (currentPath !== '/login') {
    router.replace({
      path: '/login',
      query: {
        redirect: currentPath
      }
    })
  }

  Message({
    message: '登录状态已过期，请重新登录',
    type: 'warning',
    duration: 3000
  })
}

// 处理 token 过期
function handleTokenExpired() {
  MessageBox.confirm('登录状态已过期，您可以取消停留在此页面，或重新登录', '确认退出', {
    confirmButtonText: '重新登录',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    handleUnauthorized()
  }).catch(() => {
    // 用户点击取消，不做任何操作
  })
}

// 添加重试机制
service.retry = function(config, maxRetry = 3) {
  return new Promise((resolve, reject) => {
    let retryCount = 0

    const attempt = () => {
      this.request(config)
        .then(resolve)
        .catch(error => {
          if (retryCount < maxRetry &&
              (error.response?.status >= 500 || error.code === 'ECONNABORTED')) {
            retryCount++
            console.log(`请求失败，第 ${retryCount} 次重试...`)
            setTimeout(attempt, 1000 * retryCount)
          } else {
            reject(error)
          }
        })
    }

    attempt()
  })
}

export default service
